import {
  HttpException,
  HttpStatus,
  Injectable,
  NestMiddleware,
} from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { verifyToken } from 'src/utils/utils';
import { authModel } from '../entity/auth.entity';

@Injectable()
export class AuthMiddleware implements NestMiddleware {
  async use(req: Request, res: Response, next: NextFunction) {
    const token = req.header('token');
    let obj = null;
    try {
      obj = verifyToken(token);
    } catch (err) {
      throw new HttpException(
        {
          message: '验证失败，请重新登陆',
        },
        HttpStatus.FORBIDDEN,
      );
    }
    if (typeof obj === 'object' && obj['openid']) {
      const user = await authModel.findOne({ openid: obj['openid'] });
      if (user) {
        req['user'] = user;
        next();
      } else {
        throw new HttpException(
          {
            message: '该用户不存在',
          },
          HttpStatus.FORBIDDEN,
        );
      }
    }
  }
}
